import { Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Company } from "src/modules/company/company.entity";
import { CompanyService } from "src/modules/company/company.service";
import { dateNewFirst } from "src/utils/util";
import { Repository } from "typeorm";
import { Client } from "./client.entity";
import { CreateClientDto } from "./dto/create-client.dto";
import { UpdateClientDto } from "./dto/update-client.dto";

@Injectable()
export class ClientService {
  constructor(
    @InjectRepository(Client)
    private readonly clientRepository: Repository<Client>,
    private readonly companyService: CompanyService
  ) {}

  async create(
    createClientDto: CreateClientDto,
    company: string | Company
  ): Promise<Client> {
    const client = new Client();
    company =
      company instanceof Company
        ? company
        : await this.companyService.find(company);
    Object.assign(client, createClientDto, { company });
    return this.clientRepository.save(client);
  }

  async findAll(): Promise<Client[]> {
    return (await this.clientRepository.find()).sort(dateNewFirst);
  }
  async findByCompany(companyId: string): Promise<Client[]> {
    const company = await this.companyService.find(companyId);
    return (
      await this.clientRepository.find({
        company,
      })
    ).sort(dateNewFirst);
  }
  async count(companyId?: string): Promise<number> {
    if (companyId) {
      const company = await this.companyService.find(companyId);
      return this.clientRepository.count({ company });
    }
    return this.clientRepository.count();
  }
  find(id: string): Promise<Client> {
    return this.clientRepository.findOneOrFail(id, { relations: ["company"] });
  }
  async findLast(companyId?: string): Promise<Client> {
    if (companyId) {
      const company = await this.companyService.find(companyId);
      return this.clientRepository.findOne({
        where: { company },
        order: {
          date: "DESC",
        },
      });
    }
    return this.clientRepository.findOne({
      order: {
        date: "DESC",
      },
    });
  }
  findOneWithCompany(id: string): Promise<Client> {
    return this.find(id);
  }
  async remove(client: string | Client): Promise<Client> {
    const id = client instanceof Client ? client.id : client;
    const clientToRemove = await this.find(id);
    return await this.clientRepository.remove(clientToRemove);
  }
  async update(id: string, updateClientDto: UpdateClientDto): Promise<Client> {
    const client = await this.find(id);
    Object.assign(client, updateClientDto);
    return this.clientRepository.save(client);
  }
}
